import React, { useCallback } from 'react';
import { AtImagePicker } from 'taro-ui';
import Taro from '@tarojs/taro';
import 'taro-ui/dist/style/components/image-picker.scss';
import 'taro-ui/dist/style/components/icon.scss';
import config from '../../common/config';

// 目前存在一个问题，点击删除按钮，会再弹开选择图片。issue已修复，官方版本未发
function PickerImage(props) {
  const upload = useCallback((path, isPublic, callback) => {
    Taro.uploadFile({
      url: `${config.filePrefix}/file/file/upload?public=${isPublic}`,
      filePath: path,
      name: 'file',
      header: {
        'Content-Type': 'application/x-www-form-urlencoded;text/html; charset=utf-8',
        Authorization: Taro.getStorageSync('token'),
        Client: config.client,
      },
      success(res) {
        try {
          const data = JSON.parse(res.data);
          if (data.success) {
            callback(data);
          } else {
            callback(false);
            Taro.showToast({
              title: '操作失败',
              icon: 'none',
            });
          }
        } catch (e) {
          callback(false);
        }
      },
      fail: res => {
        Taro.showToast({
          title: res.errMsg.split(' ')[1],
          icon: 'none',
        });
        callback(false);
      },
      complete() {
        // Taro.hideLoading();
      },
    });
  }, []);
  // 封装上传到数据
  const onChange = useCallback(
    (files, operationType, index) => {
      // 移除的操作
      if (operationType === 'remove') {
        props.onChangeFiles(props.files.filter((item, i) => i !== index));
        return;
      }
      // 添加操作
      // files包含了已上传、未上传的所有图片
      let newList = files.filter(item => !item.file);
      const tempList = files.filter(item => item.file);
      // 开始上传
      let num = files;
      tempList.map(tempFile => {
        // 判断文件是否过大
        if (tempFile.file && tempFile.file.size > props.maxSize) {
          Taro.showToast({
            title: `只能上传小于${props.maxSize}M的图片`,
            icon: 'none',
          });
          num--;
          return null;
        }
        // 保存当前图片的顺序
        newList.push({ ...tempFile, file: undefined });
        upload(tempFile.url, props.isPublic, data => {
          // 上传后回调的方法
          num--;
          if (num === 0) {
            Taro.hideLoading();
          }
          // 过滤上传失败的图片
          if (data && data.models[0]) {
            // 上传成功保存当前url
            newList = newList.map(item => {
              if (tempFile.url === item.url) {
                return {
                  ...item,
                  fileId: data.models[0].id,
                  fileCode: data.models[0].code,
                };
              }
              return item;
            });
          } else {
            newList = newList.filter(item => item.url !== tempFile.url);
          }

          props.onChangeFiles(newList);
        });
      });
    },
    [props, upload]
  );
  return <AtImagePicker {...props} onChange={onChange} />;
}

export default PickerImage;
